<script setup lang="ts">
import type { VbenFormSchema } from '@vben/common-ui';

import { computed, defineEmits } from 'vue';

import { useVbenForm } from '@vben/common-ui';
import { getDictOptions } from '@vben/hooks';
import { handleTree } from '@vben/utils';

import { del, download, get, post, put } from '#/api/core/http';
import { getDeptListCondition } from '#/api/system/dept';

/**
 * props:
 * - list: 后端返回的列表
 * - onSubmit: 表单提交时回调
 */
const props = defineProps({
  list: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(['submit']);

const methodMap: Record<string, any> = {
  get,
  post,
  put,
  del,
  download,
};

const safeList = computed(() => (Array.isArray(props.list) ? props.list : []));

/**
 * 动态生成表单 schema
 */
function generateSchema(list: any[]): VbenFormSchema[] {
  if (!Array.isArray(list)) return [];

  // 先按 sort 字段升序排序（数字越小越靠前）
  const sortedList = [...list].sort((a, b) => {
    const sa = Number(a.sort ?? 0);
    const sb = Number(b.sort ?? 0);
    return sa - sb;
  });
  // 再生成每个 schema 配置
  return sortedList.map((item) => {
    // 解析每个表单项的元数据（metadata）配置
    let meta: Record<string, any> = {};
    try {
      if (item.metadata) {
        meta =
          typeof item.metadata === 'string'
            ? JSON.parse(item.metadata)
            : item.metadata;
      }
    } catch (error) {
      console.warn('Metadata 解析失败:', item.metadata, error);
    }

    const schema: VbenFormSchema = {
      fieldName: item.name, // 字段名
      label: item.displayName, // 显示名称
      rules: item.required ? 'required' : undefined, // 是否必填
      defaultValue: item.defaultValue ?? undefined, // 默认值
      help: item.description, // 变量填写说明
      component: 'Input', // 默认组件
      componentProps: {
        disabled: !!item.disabled,
        placeholder: `请输入${item.displayName}`,
      },
    };

    // 根据 htmlType 映射组件
    switch (item.htmlType) {
      case 'apiCascader': {
        schema.component = 'ApiCascader';

        const placeholder = `请选择${item.displayName}`;
        const apiUrl = meta.apiUrl?.trim();
        const labelField = meta.labelField || 'label';
        const valueField = meta.valueField || 'value';
        const childrenField = meta.childrenField || 'children';

        // 1. 获取接口依赖字段
        const apiTriggerFields =
          (meta.apiParams || [])
            .filter((p: any) => p.sourceType === 'field')
            .map((p: any) => p.value)
            .filter(Boolean) || [];

        // 2. 获取显示逻辑依赖字段
        let displayTriggerFields: string[] = [];
        if (item.displayFlag === 'dynamic') {
          if (Array.isArray(meta.hiddenByField)) {
            displayTriggerFields = meta.hiddenByField;
          } else if (meta.hiddenByField) {
            displayTriggerFields = [meta.hiddenByField];
          }
        }

        // 3. 合并去重，保证至少一个元素
        const triggerFieldsArr = [
          ...new Set([...apiTriggerFields, ...displayTriggerFields]),
        ];
        const triggerFields =
          triggerFieldsArr.length > 0 ? triggerFieldsArr : [''];

        schema.dependencies = {
          triggerFields,
          show: (values) => {
            if (item.displayFlag === false || item.displayFlag === 0)
              return false;
            if (item.displayFlag === 'dynamic') {
              const hiddenFields = [...(meta.hiddenByField || [])];
              return hiddenFields.every(
                (f) =>
                  values[f] !== undefined &&
                  values[f] !== null &&
                  values[f] !== '',
              );
            }
            return true; // 默认显示
          },
          disabled: () => !!item.disabled,
          componentProps: async (values) => {
            const key =
              triggerFields.length > 0
                ? JSON.stringify(triggerFields.map((f) => values?.[f] ?? null))
                : 'all';

            return {
              key,
              placeholder,
              allowClear: true,
              showSearch: true,
              optionFilterProp: labelField,
              fieldNames: {
                label: labelField,
                value: valueField,
                children: childrenField,
              },
              changeOnSelect: meta.changeOnSelect ?? false,

              onChange: (value: any, option: any) => {
                if (meta.onChangeFlag && meta.onChangeMessage) {
                  try {
                    const fn = new Function(
                      'values',
                      'option',
                      meta.onChangeMessage,
                    );
                    fn(values, option);
                  } catch (error) {
                    console.error('执行 onChangeMessage 失败:', error);
                  }
                }
              },
              api: async () => {
                if (!apiUrl) return [];
                try {
                  const method =
                    methodMap[meta.apiMethod?.toLowerCase() || 'post'];
                  if (!method)
                    throw new Error(`不支持的请求方式: ${meta.apiMethod}`);

                  // 解析接口参数
                  let apiParamsList: any[] = [];
                  try {
                    apiParamsList = Array.isArray(meta.apiParams)
                      ? meta.apiParams
                      : JSON.parse(meta.apiParams || '[]');
                  } catch {
                    apiParamsList = [];
                  }

                  const paramsObj: Record<string, any> = {};
                  apiParamsList.forEach((p: any) => {
                    if (!p.paramKey) return;
                    if (p.sourceType === 'fixed')
                      paramsObj[p.paramKey] = p.value;
                    else if (p.sourceType === 'field')
                      paramsObj[p.paramKey] = values?.[p.value] ?? null;
                  });

                  const res = await method(apiUrl, paramsObj);
                  const data = Array.isArray(res) ? res : res?.data || [];
                  return handleTree(data, {
                    labelField,
                    valueField,
                    childrenField,
                  });
                } catch (error) {
                  console.error(`API Cascader 加载失败: ${apiUrl}`, error);
                  return [];
                }
              },
            };
          },
        };

        break;
      }

      case 'apiPagingSelect': {
        schema.component = 'ApiPagingSelect';

        const placeholder = `请选择${item.displayName}`;
        const apiUrl = meta.apiUrl?.trim();
        const labelField = meta.labelField || 'label';
        const valueField = meta.valueField || 'value';

        // 1. 获取接口依赖字段
        const apiTriggerFields =
          (meta.apiParams || [])
            .filter((p: any) => p.sourceType === 'field')
            .map((p: any) => p.value)
            .filter(Boolean) || [];

        // 2. 获取显示逻辑依赖字段
        let displayTriggerFields: string[] = [];
        if (item.displayFlag === 'dynamic') {
          if (Array.isArray(meta.hiddenByField)) {
            displayTriggerFields = meta.hiddenByField;
          } else if (meta.hiddenByField) {
            displayTriggerFields = [meta.hiddenByField];
          }
        }

        // 3. 合并去重
        const triggerFields = [
          ...new Set([...apiTriggerFields, ...displayTriggerFields]),
        ];

        if (triggerFields.length === 0) {
          triggerFields.push('');
        }

        schema.dependencies = {
          triggerFields,
          show: (values) => {
            if (item.displayFlag === false || item.displayFlag === 0)
              return false;

            if (item.displayFlag === 'dynamic') {
              const hiddenFields = [...(meta.hiddenByField || [])];
              return hiddenFields.every(
                (f) =>
                  values[f] !== undefined &&
                  values[f] !== null &&
                  values[f] !== '',
              );
            }

            return true; // 默认显示
          },
          disabled: () => !!item.disabled,
          componentProps: async (values) => {
            const key =
              triggerFields.length > 0
                ? JSON.stringify(triggerFields.map((f) => values?.[f] ?? null))
                : 'all';

            return {
              key,
              placeholder,
              showSearch: true,
              allowClear: true,
              optionFilterProp: 'label',

              onChange: (value: any, option: any) => {
                if (meta.onChangeFlag && meta.onChangeMessage) {
                  try {
                    const fn = new Function(
                      'values',
                      'option',
                      meta.onChangeMessage,
                    );
                    fn(values, option);
                  } catch (error) {
                    console.error('执行 onChangeMessage 失败:', error);
                  }
                }
              },
              api: async () => {
                if (!apiUrl) return [];
                try {
                  const method =
                    methodMap[meta.apiMethod?.toLowerCase() || 'post'];
                  if (!method)
                    throw new Error(`不支持的请求方式: ${meta.apiMethod}`);

                  // 解析接口参数
                  let apiParamsList: any[] = [];
                  try {
                    apiParamsList = Array.isArray(meta.apiParams)
                      ? meta.apiParams
                      : JSON.parse(meta.apiParams || '[]');
                  } catch {
                    apiParamsList = [];
                  }

                  const paramsObj: Record<string, any> = {};
                  apiParamsList.forEach((p: any) => {
                    if (!p.paramKey) return;
                    if (p.sourceType === 'fixed')
                      paramsObj[p.paramKey] = p.value;
                    else if (p.sourceType === 'field')
                      paramsObj[p.paramKey] = values?.[p.value] ?? null;
                  });

                  const res = await method(apiUrl, paramsObj);
                  const data = Array.isArray(res) ? res : res?.data || [];

                  return data.map((v: any) => ({
                    label: v[labelField] ?? '',
                    value: v[valueField] ?? '',
                    ...v,
                  }));
                } catch (error) {
                  console.error(`API Paging Select 加载失败: ${apiUrl}`, error);
                  return [];
                }
              },
            };
          },
        };

        break;
      }

      case 'apiSelect': {
        schema.component = 'ApiSelect';
        const placeholder = `请选择${item.displayName}`;
        const apiUrl = meta.apiUrl?.trim();
        const labelField = meta.labelField || 'label';
        const valueField = meta.valueField || 'value';

        // 1. 获取接口依赖字段
        const apiTriggerFields =
          (meta.apiParams || [])
            .filter((p: any) => p.sourceType === 'field')
            .map((p: any) => p.value) || [];

        // 2. 获取显示逻辑依赖字段
        let displayTriggerFields: string[] = [];
        if (item.displayFlag === 'dynamic') {
          if (Array.isArray(meta.hiddenByField)) {
            displayTriggerFields = meta.hiddenByField;
          } else if (meta.hiddenByField) {
            displayTriggerFields = [meta.hiddenByField];
          }
        }
        // 3. 合并去重
        const triggerFields = [
          ...new Set([...apiTriggerFields, ...displayTriggerFields]),
        ];

        if (triggerFields.length === 0) {
          triggerFields.push('');
        }
        debugger;
        schema.dependencies = {
          triggerFields,
          show: (values) => {
            if (item.displayFlag === false || item.displayFlag === 0)
              return false;

            if (item.displayFlag === 'dynamic') {
              const hiddenFields = [...(meta.hiddenByField || [])];
              // 当关联字段任意一个值为空时隐藏（可根据需要调整逻辑）
              return hiddenFields.every(
                (f) =>
                  values[f] !== undefined &&
                  values[f] !== null &&
                  values[f] !== '',
              );
            }

            // 默认：显示
            return true;
          },
          disabled: () => !!item.disabled,
          componentProps: async (values) => {
            const key =
              triggerFields.length > 0
                ? JSON.stringify(triggerFields.map((f) => values?.[f] ?? null))
                : 'all';
            return {
              key,
              placeholder,
              showSearch: true,
              allowClear: true,
              optionFilterProp: 'label',

              onChange: (value: any, option: any) => {
                if (meta.onChangeFlag && meta.onChangeMessage) {
                  try {
                    const fn = new Function(
                      'values',
                      'option',
                      meta.onChangeMessage,
                    );
                    fn(values, option);
                  } catch (error) {
                    console.error('执行 onChangeMessage 失败:', error);
                  }
                }
              },

              api: async () => {
                if (!apiUrl) return [];
                try {
                  const method =
                    methodMap[meta.apiMethod?.toLowerCase() || 'post'];
                  if (!method)
                    throw new Error(`不支持的请求方式: ${meta.apiMethod}`);

                  let apiParamsList: any[] = [];
                  try {
                    apiParamsList = Array.isArray(meta.apiParams)
                      ? meta.apiParams
                      : JSON.parse(meta.apiParams || '[]');
                  } catch {
                    apiParamsList = [];
                  }

                  const paramsObj: Record<string, any> = {};
                  apiParamsList.forEach((p: any) => {
                    if (!p.paramKey) return;
                    if (p.sourceType === 'fixed')
                      paramsObj[p.paramKey] = p.value;
                    else if (p.sourceType === 'field')
                      paramsObj[p.paramKey] = values?.[p.value] ?? null;
                  });

                  const res = await method(apiUrl, paramsObj);
                  const data = Array.isArray(res) ? res : res?.data || [];
                  return data.map((v: any) => ({
                    label: v[labelField] ?? '',
                    value: v[valueField] ?? '',
                    ...v,
                  }));
                } catch (error) {
                  console.error(`API Select 加载失败: ${apiUrl}`, error);
                  return [];
                }
              },
            };
          },
        };

        break;
      }

      case 'autoComplete': {
        schema.component = 'AutoComplete';
        break;
      }

      case 'checkbox': {
        // 多选复选框组件
        schema.component = 'CheckboxGroup';

        const isCustom = meta.isCustomOptions ?? false;
        const dictType = meta.dictType || '';
        const dictOptions = meta.dictOptions || [];

        const placeholder = `请选择${item.displayName}`;

        // 获取选项列表
        if (!isCustom && dictType) {
          const options = getDictOptions(dictType).map((opt) => ({
            ...opt,
            value: String(opt.value), //  强制字符串类型，避免选中异常
          }));

          schema.componentProps = {
            placeholder,
            options,
          };
        } else {
          const options = dictOptions.map((opt) => ({
            label: opt.label ?? opt.dictLabel ?? opt.name ?? '',
            value: String(opt.value ?? opt.dictValue ?? ''), //  统一字符串
          }));

          schema.componentProps = {
            placeholder,
            options,
            ...schema.componentProps,
          };
        }
        break;
      }

      case 'color': {
        schema.component = 'ColorPicker';
        break;
      }

      /** 日期/时间组件统一处理 */
      case 'date':
      case 'datetime':
      case 'month':
      case 'time':
      case 'year': {
        schema.component = 'DatePicker';

        // 根据类型动态配置属性
        const typeMap: Record<string, any> = {
          datetime: {
            showTime: true,
            format: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'x',
            placeholder: `请选择${item.displayName || '日期时间'}`,
          },
          time: {
            picker: 'time',
            format: 'HH:mm:ss',
            valueFormat: 'x',
            placeholder: `请选择${item.displayName || '时间'}`,
          },
          date: {
            picker: 'date',
            format: 'YYYY-MM-DD',
            valueFormat: 'x',
            placeholder: `请选择${item.displayName || '日期'}`,
          },
          month: {
            picker: 'month',
            format: 'YYYY-MM',
            valueFormat: 'x',
            placeholder: `请选择${item.displayName || '月份'}`,
          },
          year: {
            picker: 'year',
            format: 'YYYY',
            valueFormat: 'x',
            placeholder: `请选择${item.displayName || '年份'}`,
          },
        };

        const config = typeMap[item.htmlType] || typeMap.date;

        schema.componentProps = {
          ...config,
        };

        break;
      }
      case 'editor': {
        schema.component = 'RichTextarea';
        break;
      }
      case 'fileUpload': {
        schema.component = 'FileUpload';

        // 读取元数据配置
        const {
          minNumber = 0,
          maxNumber = 1,
          fileCategoriesCode = '',
          objectId = '',
          objectType = '',
        } = meta || {};

        // 组装上传参数
        const uploadParams = {
          fileCategoriesCode,
          objectId,
          objectType,
        };

        schema.componentProps = {
          // 基本参数
          maxNumber,
          minNumber,
          params: uploadParams,

          // 默认占位符
          placeholder:
            meta.placeholder || `请上传${item.displayName || '文件'}`,
        };

        break;
      }
      case 'icon': {
        schema.component = 'IconPicker';
        break;
      }

      /** 图片上传组件 */
      case 'imageUpload': {
        schema.component = 'ImageUpload';

        // 读取元数据配置
        const {
          minNumber = 0,
          maxNumber = 1,
          fileCategoriesCode = '',
          objectId = '',
          objectType = '',
        } = meta || {};

        // 组装上传参数
        const uploadParams = {
          fileCategoriesCode,
          objectId,
          objectType,
        };

        schema.componentProps = {
          // 基本参数
          maxNumber,
          minNumber,
          params: uploadParams,

          // 可扩展自定义属性

          // 默认占位符
          placeholder:
            meta.placeholder || `请上传${item.displayName || '图片'}`,
        };

        break;
      }
      case 'input': {
        schema.component = 'Input';
        const placeholder = `请输入${item.displayName}`;

        // 获取显示逻辑依赖字段
        let displayTriggerFields: string[] = [];
        if (item.displayFlag === 'dynamic') {
          if (Array.isArray(meta.hiddenByField)) {
            displayTriggerFields = meta.hiddenByField;
          } else if (meta.hiddenByField) {
            displayTriggerFields = [meta.hiddenByField];
          }
        }

        // 合并去重，保证至少有一个元素
        const triggerFieldsArr = [...new Set(displayTriggerFields)];
        const triggerFields =
          triggerFieldsArr.length > 0 ? triggerFieldsArr : [''];

        schema.dependencies = {
          triggerFields,
          show: (values) => {
            if (item.displayFlag === false || item.displayFlag === 0)
              return false;

            if (item.displayFlag === 'dynamic') {
              const hiddenFields = [...(meta.hiddenByField || [])];
              return hiddenFields.every(
                (f) =>
                  values[f] !== undefined &&
                  values[f] !== null &&
                  values[f] !== '',
              );
            }

            return true; // 默认显示
          },
          disabled: () => !!item.disabled, // 动态禁用逻辑
          componentProps: (values) => ({
            key:
              triggerFields.length > 0
                ? JSON.stringify(triggerFields.map((f) => values[f] ?? null))
                : 'all',
            placeholder,

            onChange: (value: any) => {
              if (meta.onChangeFlag && meta.onChangeMessage) {
                try {
                  const fn = new Function(
                    'values',
                    'value',
                    meta.onChangeMessage,
                  );
                  fn(values, value);
                } catch (error) {
                  console.error('执行 onChangeMessage 失败:', error);
                }
              }
            },
          }),
        };

        break;
      }

      case 'inputNumber': {
        schema.component = 'InputNumber';
        const placeholder = `请输入${item.displayName}`;

        // 获取显示逻辑依赖字段
        let displayTriggerFields: string[] = [];
        if (item.displayFlag === 'dynamic') {
          if (Array.isArray(meta.hiddenByField)) {
            displayTriggerFields = meta.hiddenByField;
          } else if (meta.hiddenByField) {
            displayTriggerFields = [meta.hiddenByField];
          }
        }

        // 合并去重，保证至少有一个元素
        const triggerFieldsArr = [...new Set(displayTriggerFields)];
        const triggerFields =
          triggerFieldsArr.length > 0 ? triggerFieldsArr : [''];

        schema.dependencies = {
          triggerFields,
          show: (values) => {
            if (item.displayFlag === false || item.displayFlag === 0)
              return false;

            if (item.displayFlag === 'dynamic') {
              const hiddenFields = [...(meta.hiddenByField || [])];
              return hiddenFields.every(
                (f) =>
                  values[f] !== undefined &&
                  values[f] !== null &&
                  values[f] !== '',
              );
            }

            return true; // 默认显示
          },
          disabled: () => !!item.disabled, // 动态禁用逻辑
          componentProps: (values) => ({
            key:
              triggerFields.length > 0
                ? JSON.stringify(triggerFields.map((f) => values[f] ?? null))
                : 'all',
            placeholder,

            onChange: (value: any) => {
              if (meta.onChangeFlag && meta.onChangeMessage) {
                try {
                  const fn = new Function(
                    'values',
                    'value',
                    meta.onChangeMessage,
                  );
                  fn(values, value);
                } catch (error) {
                  console.error('执行 onChangeMessage 失败:', error);
                }
              }
            },
          }),
        };

        break;
      }

      case 'inputPassword': {
        schema.component = 'InputPassword';
        break;
      }

      case 'markdownEditor': {
        schema.component = 'MarkdownEditor';
        break;
      }
      case 'radio': {
        schema.component = 'RadioGroup';

        const placeholder = `请选择${item.displayName}`;
        const isCustom = meta.isCustomOptions ?? false;
        const dictType = meta.dictType || '';
        const dictOptions = meta.dictOptions || [];

        // 系统字典模式
        if (!isCustom && dictType) {
          try {
            schema.componentProps = {
              placeholder,
              options: getDictOptions(dictType), // 支持系统字典
              buttonStyle: 'solid',
              optionType: 'button',
            };
          } catch (error) {
            console.error(`加载系统字典(${dictType})失败:`, error);
            schema.componentProps = {
              placeholder,
              options: [],
              buttonStyle: 'solid',
              optionType: 'button',
            };
          }
        }
        // 自定义字典模式
        else {
          schema.componentProps = {
            placeholder,
            options: dictOptions.map((opt: any) => ({
              label: opt.label ?? opt.dictLabel ?? opt.name ?? '',
              value: opt.value ?? opt.dictValue ?? '',
            })),
            buttonStyle: 'solid',
            optionType: 'button',
          };
        }

        break;
      }
      case 'rate': {
        schema.component = 'Rate';

        // 默认参数
        const rateCount = Number(meta.rateCount ?? 10);
        const allowHalf = Boolean(meta.allowHalf ?? false);
        const defaultValue = meta.defaultValue ?? 0;

        schema.componentProps = {
          count: rateCount, // 星星总数
          allowHalf, // 是否允许半分
        };

        // 默认值
        schema.defaultValue = defaultValue;

        break;
      }
      case 'select': {
        schema.component = 'Select';
        const dictMode = meta.dictMode ?? ''; // '', 'multiple', 'tags'
        const placeholder = `请选择${item.displayName}`;

        // 1. 获取接口依赖字段（如果是接口字典的话）
        const apiTriggerFields =
          (meta.apiParams || [])
            .filter((p: any) => p.sourceType === 'field')
            .map((p: any) => p.value)
            .filter(Boolean) || [];

        // 2. 获取显示逻辑依赖字段
        let displayTriggerFields: string[] = [];
        if (item.displayFlag === 'dynamic') {
          if (Array.isArray(meta.hiddenByField)) {
            displayTriggerFields = meta.hiddenByField;
          } else if (meta.hiddenByField) {
            displayTriggerFields = [meta.hiddenByField];
          }
        }

        // 3. 合并去重，保证至少有一个元素
        const triggerFieldsArr = [
          ...new Set([...apiTriggerFields, ...displayTriggerFields]),
        ];
        const triggerFields =
          triggerFieldsArr.length > 0 ? triggerFieldsArr : [''];

        schema.dependencies = {
          triggerFields,
          show: (values) => {
            if (item.displayFlag === false || item.displayFlag === 0)
              return false;
            if (item.displayFlag === 'dynamic') {
              const hiddenFields = [...(meta.hiddenByField || [])];
              return hiddenFields.every(
                (f) =>
                  values[f] !== undefined &&
                  values[f] !== null &&
                  values[f] !== '',
              );
            }
            return true; // 默认显示
          },
          disabled: () => !!item.disabled,
          componentProps: async (values) => {
            const key =
              triggerFields.length > 0
                ? JSON.stringify(triggerFields.map((f) => values?.[f] ?? null))
                : 'all';

            // 如果是自定义字典或系统字典
            let options: any[] = [];
            if (meta.isCustomOptions) {
              options = meta.dictOptions || [];
            } else if (meta.dictType) {
              options = getDictOptions(meta.dictType, 'number');
            }

            return {
              key,
              placeholder,
              mode: dictMode,
              allowClear: true,
              options,

              onChange: (value: any, option: any) => {
                if (meta.onChangeFlag && meta.onChangeMessage) {
                  try {
                    const fn = new Function(
                      'values',
                      'option',
                      meta.onChangeMessage,
                    );
                    fn(values, option);
                  } catch (error) {
                    console.error('执行 onChangeMessage 失败:', error);
                  }
                }
              },
            };
          },
        };

        break;
      }

      // 区域/单位/部门级联
      case 'selectArea':
      case 'selectDept':
      case 'selectUnit': {
        const typeMap: Record<string, 'area' | 'dept' | 'unit'> = {
          selectArea: 'area',
          selectUnit: 'unit',
          selectDept: 'dept',
        };
        const type = typeMap[item.htmlType];

        let triggerField = '';
        let keyField = '';
        let placeholder = '';

        if (type === 'area') placeholder = '请选择行政区划';
        if (type === 'unit') {
          placeholder = '请选择单位';
          triggerField = 'areaCode';
          keyField = 'areaCode';
        }
        if (type === 'dept') {
          placeholder = '请选择归属部门';
          triggerField = 'unitId';
          keyField = 'unitId';
        }

        schema.component = 'ApiTreeSelect';
        schema.componentProps = {
          placeholder,
          labelField: 'name',
          valueField: 'id',
          childrenField: 'children',
          treeDefaultExpandAll: type === 'area',
          allowClear: true,
          api: async (values?: Record<string, any>) => {
            const params: Record<string, any> = { type };
            if (values && keyField && values[keyField])
              params[keyField] = values[keyField];
            const data = await getDeptListCondition(params);
            return handleTree(data);
          },
        };

        if (triggerField) {
          schema.dependencies = {
            triggerFields: [triggerField],
            componentProps: (values) => ({
              ...schema.componentProps,
              key: values[keyField] || 'all',
            }),
            trigger(values, formApi) {
              formApi.setFieldValue(item.name, undefined);
            },
          };
        }
        break;
      }

      case 'selectTree': {
        schema.component = 'ApiTreeSelect';

        const placeholder = `请选择${item.displayName}`;
        const apiUrl = meta.apiUrl?.trim();
        const labelField = meta.labelField || 'label';
        const valueField = meta.valueField || 'value';
        const childrenField = meta.childrenField || 'children';

        // 1. 获取接口依赖字段
        const apiTriggerFields =
          (meta.apiParams || [])
            .filter((p: any) => p.sourceType === 'field')
            .map((p: any) => p.value)
            .filter(Boolean) || [];

        // 2. 获取显示逻辑依赖字段
        let displayTriggerFields: string[] = [];
        if (item.displayFlag === 'dynamic') {
          if (Array.isArray(meta.hiddenByField)) {
            displayTriggerFields = meta.hiddenByField;
          } else if (meta.hiddenByField) {
            displayTriggerFields = [meta.hiddenByField];
          }
        }

        // 3. 合并去重，保证至少有一个元素
        const triggerFieldsArr = [
          ...new Set([...apiTriggerFields, ...displayTriggerFields]),
        ];
        const triggerFields =
          triggerFieldsArr.length > 0 ? triggerFieldsArr : [''];

        schema.dependencies = {
          triggerFields,
          show: (values) => {
            if (item.displayFlag === false || item.displayFlag === 0)
              return false;
            if (item.displayFlag === 'dynamic') {
              const hiddenFields = [...(meta.hiddenByField || [])];
              return hiddenFields.every(
                (f) =>
                  values[f] !== undefined &&
                  values[f] !== null &&
                  values[f] !== '',
              );
            }
            return true; // 默认显示
          },
          disabled: () => !!item.disabled,
          componentProps: async (values) => {
            const key =
              triggerFields.length > 0
                ? JSON.stringify(triggerFields.map((f) => values?.[f] ?? null))
                : 'all';

            return {
              key,
              placeholder,
              allowClear: true,
              treeDefaultExpandAll: true,
              showSearch: true,
              optionFilterProp: 'label',
              labelField,
              valueField,
              childrenField,

              onChange: (value: any, option: any) => {
                if (meta.onChangeFlag && meta.onChangeMessage) {
                  try {
                    const fn = new Function(
                      'values',
                      'option',
                      meta.onChangeMessage,
                    );
                    fn(values, option);
                  } catch (error) {
                    console.error('执行 onChangeMessage 失败:', error);
                  }
                }
              },
              api: async () => {
                if (!apiUrl) return [];
                try {
                  const method =
                    methodMap[meta.apiMethod?.toLowerCase() || 'post'];
                  if (!method)
                    throw new Error(`不支持的请求方式: ${meta.apiMethod}`);

                  // 解析接口参数
                  let apiParamsList: any[] = [];
                  try {
                    apiParamsList = Array.isArray(meta.apiParams)
                      ? meta.apiParams
                      : JSON.parse(meta.apiParams || '[]');
                  } catch {
                    apiParamsList = [];
                  }

                  const paramsObj: Record<string, any> = {};
                  apiParamsList.forEach((p: any) => {
                    if (!p.paramKey) return;
                    if (p.sourceType === 'fixed')
                      paramsObj[p.paramKey] = p.value;
                    else if (p.sourceType === 'field')
                      paramsObj[p.paramKey] = values?.[p.value] ?? null;
                  });

                  const res = await method(apiUrl, paramsObj);
                  const data = Array.isArray(res) ? res : res?.data || [];

                  return handleTree(data);
                } catch (error) {
                  console.error(`API TreeSelect 加载失败: ${apiUrl}`, error);
                  return [];
                }
              },
            };
          },
        };

        break;
      }

      case 'selectUser': {
        schema.component = 'ApiSelect';
        break;
      }
      case 'switch': {
        schema.component = 'Switch';
        break;
      }
      case 'textarea': {
        schema.component = 'Textarea';
        break;
      }

      default: {
        schema.component = 'Input';
      }
    }

    // 3. 只有特定类型才加 dependencies
    if (
      item.htmlType !== 'apiCascader' &&
      item.htmlType !== 'apiPagingSelect' &&
      item.htmlType !== 'apiSelect' &&
      item.htmlType !== 'select' &&
      item.htmlType !== 'selectTree' &&
      item.htmlType !== 'input' &&
      item.htmlType !== 'inputNumber'
    ) {
      // 先计算依赖字段
      let displayTriggerFields: string[] = [];
      if (item.displayFlag === 'dynamic') {
        if (Array.isArray(meta.hiddenByField)) {
          displayTriggerFields = meta.hiddenByField;
        } else if (meta.hiddenByField) {
          displayTriggerFields = [meta.hiddenByField];
        }
      }

      // 合并去重
      const triggerFields = [...new Set(displayTriggerFields)];
      if (triggerFields.length === 0) {
        triggerFields.push('');
      }

      schema.dependencies = {
        triggerFields,
        show: (values) => {
          if (item.displayFlag === false || item.displayFlag === 0)
            return false;

          if (item.displayFlag === 'dynamic') {
            const hiddenFields = [...(meta.hiddenByField || [])];
            // 当关联字段任意一个值为空时隐藏（可根据需要调整逻辑）
            return hiddenFields.every(
              (f) =>
                values[f] !== undefined &&
                values[f] !== null &&
                values[f] !== '',
            );
          }

          // 默认：显示
          return true;
        },
        disabled: () => !!item.disabled,
      };
    }
    return schema;
  });
}

const dynamicSchema = computed(() => generateSchema(safeList.value));

const [Form, formApi] = useVbenForm({
  schema: dynamicSchema,
  layout: 'horizontal',
  showDefaultActions: false,
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    labelWidth: 80,
  },
  // 一共1列
  wrapperClass: 'grid-cols-1',
});

/**
 * 返回表单内容
 */
async function onSubmit() {
  const { valid } = await formApi.validate();
  if (!valid) return;
  const values = await formApi.getValues();
  emit('submit', values);
}
</script>

<template>
  <div>
    <Form @submit="onSubmit" />
  </div>
</template>
